import store from '../store/index.js'
/*
* @params url 请求api地址
* @params methods  请求方式
*/
import { baseUtils } from './base.js';

const $http = async (apiUrl,methods,data,config) =>{
	let baseUrl = baseUtils.baseUrl();
	let token = uni.getStorageSync('token') || '';
	let user = uni.getStorageSync('userInfo') || '';
	let header = {
		"Content-Type": "application/json;charset=utf-8",
		"token":token,
		"user_id": (user && user != '') ? user.userId : '',
		"service_version":baseUtils.version()
	}
	if(config && config.FORM){
		header["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
	}
	//设置定时 1秒之内的接口返回不显示加载中...
	let times = null;
	let s = 800;  //设置加载延时时间
	if(config && config.NONE){

	}else{
		if(config && config.NOW){
			s=0;
		};
		times = setTimeout(()=>{
			uni.showLoading({
				title:'加载中...',
				mask:true,
			})
		},s);
	};
	/// 默认
	return new Promise((resolve, reject)=>{
		uni.request({
			url:baseUrl+apiUrl,
			method:methods,
			data:data,
			header:header,
			success:function(res){
				if(res.data.code == '401' || res.data.code == '601'){
					store.commit('USER_IF_LOGIN',false);
					uni.setStorageSync('login',false);
					uni.reLaunch({
						url:'/pages/login/login'
					});
					uni.showToast({
						title:'登录失效了，请重新登录～',
						icon:'none'

					})
				}else{
					resolve(res);
				};
				clearTimeout(times);
				uni.hideLoading();
				setTimeout(()=>{
					clearTimeout(times);
					uni.hideLoading();
				},800);
			},
			fail:function(e){
				reject(e);
				clearTimeout(times);
				uni.hideLoading();
				setTimeout(()=>{
					clearTimeout(times);
					uni.hideLoading();
				},800);
				uni.showToast({
					icon:'none',
					title:'连接失败',
					duration:1500
				})
			}
		})
	});
}

export default $http;
